#!/usr/bin/env python3
## @file
#  Check a patch for various format issues
#
#  Copyright (c) 2015, Intel Corporation. All rights reserved.<BR>
#
#  This program and the accompanying materials are licensed and made
#  available under the terms and conditions of the BSD License which
#  accompanies this distribution. The full text of the license may be
#  found at http://opensource.org/licenses/bsd-license.php
#
#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS"
#  BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER
#  EXPRESS OR IMPLIED.
#

from __future__ import print_function

VersionNumber = '0.1'
__copyright__ = "Copyright (c) 2015, Intel Corporation  All rights reserved."

import argparse
import os
import re
import subprocess
import sys
import tempfile

class RunPandoc:

    def __init__(self, src, dst):
        self.run_pandoc('-f', 'mediawiki', '-t', 'markdown_github',
                        '-s', src, '-o', dst)
        self.ok = True

    def run_pandoc(self, *args):
        cmd = [ 'pandoc' ]
        cmd += args
        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        return p.communicate()[0].decode('utf-8', 'ignore')

class FixupMarkdown:

    def __init__(self, filename):
        d = open(filename, 'rb').read().decode('utf-8')
        start = 0

        result = self.wikilink_re.sub(self.replacer, d)
        if result != d:
            open(filename, 'wb').write(result.encode('utf-8'))
        self.ok = True

    def replacer(self, mo):
        if mo.group('link').replace(' ', '_') == mo.group('url'):
            return '[[' + mo.group('link') + ']]'
        else:
            return mo.group()

    wikilink_re = \
        re.compile(r'''
                       \[ (?P<link> [^]]+ ) \]
                       \(
                           (?P<url> [^)]+ )
                           \s + "wikilink"
                       \)
                   ''',
                   re.IGNORECASE | re.VERBOSE | re.MULTILINE)

class GitCommit:

    def __init__(self, base, src, dst):
        self.run_git('add', dst)
        self.run_git('rm', src)
        f = tempfile.NamedTemporaryFile(delete=False)
        f.write(('{0}: Convert to markdown with mediawiki-to-md ' +
                 'script').format(base).encode('utf-8'))
        f.close()
        self.run_git('commit', '-sF', f.name)
        self.ok = True

    def run_git(self, *args):
        cmd = [ 'git' ]
        cmd += args
        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        result = p.communicate()[0].decode('utf-8', 'ignore')
        if p.returncode != 0:
            print('git failed:\n', result)
            assert(p.returncode == 0)
        return result

class App:

    def __init__(self):
        self.parse_options()
        files = self.args.files

        self.ok = True
        for filename in files:
            if self.ok:
                self.process_one_arg(filename)

        if self.ok:
            self.retval = 0
        else:
            self.retval = 1

    def process_one_arg(self, src):
        if not src.endswith('.mediawiki'):
            src += '.mediawiki'
        assert(os.path.exists(src))
        base = os.path.splitext(src)[0]
        dst = base + '.md'
        self.ok &= RunPandoc(src, dst).ok
        if not self.ok:
            return

        self.ok &= FixupMarkdown(dst).ok
        if not self.ok:
            return

        self.ok &= GitCommit(base, src, dst).ok

    def parse_options(self):
        parser = argparse.ArgumentParser(description=__copyright__)
        parser.add_argument('--version', action='version',
                            version='%(prog)s ' + VersionNumber)
        parser.add_argument('files', nargs='+',
                            help='Mediawiki file')
        self.args = parser.parse_args()

if __name__ == "__main__":
    sys.exit(App().retval)
